package com.pcbly.web.persistence.workflow;

import java.util.List;

import org.hibernate.Query;
 
import com.pcbly.web.bean.workflow.WorkflowStepBean;
import com.pcbly.web.components.utils.random.GUID;
import com.pcbly.web.persistence.HibernateBaseDao;

@SuppressWarnings("unchecked")
public class WorkflowStepHibernateDao extends
		HibernateBaseDao<WorkflowStepBean> implements WorkflowStepDao {

	/**
	 * 
	 */
	private static final long serialVersionUID = -3003425606253103270L;

	public WorkflowStepHibernateDao() {
		super();
	}

	protected Class<WorkflowStepBean> getEntityClass() {
		return WorkflowStepBean.class;
	}

	@Override
	public void createWorkflowStepBean(WorkflowStepBean bean) throws Exception {
		// TODO Auto-generated method stub
		bean.setId((new GUID()).toString());
		getSession().save(bean);
	}

	
	@Override
	public List<WorkflowStepBean> findWorkflowStepBeanByTIdAndIndex(
			String templateId, String index, boolean equal) throws Exception {
		// TODO Auto-generated method stub
		StringBuilder sb= new StringBuilder("select wfs  from WorkflowStepBean  wfs ");
		sb.append(" where wfs.workflowTemplate.id=? ");
		
		if(equal){
			sb.append(" and wfs.index=? ");
		}else{
			sb.append(" and wfs.index>? ");
		}	
		Query query= getSession().createQuery(sb.toString());
		query.setString(0, templateId);
		query.setInteger(1, new Integer(index));
		
		return query.list();
	}

	@Override
	public WorkflowStepBean findWorkflowStepBeanByTempIdAndStepName(
			String templateId, String name) throws Exception {
		// TODO Auto-generated method stub
		StringBuilder hqlsb= new StringBuilder(" from WorkflowStepBean as wfs " );
		hqlsb.append(" where wfs.workflowTemplate.id=? ");
		hqlsb.append("  and wfs.stepName=?");
		Query query= getSession().createQuery(hqlsb.toString());
		query.setString(0, templateId);
		query.setString(1, name);
		
		WorkflowStepBean step=(WorkflowStepBean)query.uniqueResult();
		return step;
	}

	@Override
	public List<WorkflowStepBean> findWorkflowStepBeanByTemplateId(
			String templateId) throws Exception {
		// TODO Auto-generated method stub
		StringBuilder sb=new StringBuilder("");
		sb.append("select a from  WorkflowStepBean a ");
		sb.append(" where a.workflowTemplate.id=? ");
		Query query= getSession().createQuery(sb.toString());
		query.setString(0, templateId);		
		return query.list();
	}
	
}
